<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Face Recognition Demo</title>
    <link rel=stylesheet type="text/css" href="/static/css/main.css">
    <link rel="shortcut icon" href="/static/css/favicon.ico" type="image/x-icon"/>
</head>
<body>
    <h1 align="center">
        <b><i>人脸入库</i></b>&nbsp;
        <a href="./" style="font-size: 14px;">人脸识别</a>
    </h1>
    <div class='area'>
        <span class="btn-gen" onclick="javascript:$('#rapid_face').click();">试试你的图片?（可拖拽、粘贴、点击）</span>
        <input type="file" style="display: none;" name="pic" id="rapid_face"/>
        <span class="uplodNote">支持PNG、JPG、JPEG、BMP，图片大小不超过3M。</span>
    </div>
    <br/>
    <div class="area">
        <div class="leftarea" id="detectDiv">
            <span class="span_title">人 脸 入 库 图 片</span><br/><br/>
            <div class="wrapper" id="wrapper" hidden></div>
            <img id="detect_img" src=""/>
        </div>

        <div class="rightarea" id="recogDiv">
            <span id="rec_res" class="span_title">基 本 信 息 录 入</span>
            <br/><br/>
            <div id="base_info" style="text-align: left;margin-left: 5%;">
                <div >
                    <span>中文姓名：</span>
                    <input type="text" id="name" placeholder="请输入姓名" style="height:25px;"/>
                </div>
                <div style="margin-top: 20px;">
                    <span >唯一标识：</span>
                    <input type="text" id="uuid" placeholder="请输入唯一标识" style="height:25px;"/>
                </div>
                <div style="margin-top: 20px;">
                    <span class="btn-gen" onclick="faceSave()">人脸数据录入</span>
                </div>
            </div>
        </div>
    </div>
    <script src="{{url_for('static', filename='js/jquery-3.0.0.min.js')}}"></script>
    <script type="text/javascript">
        // 页面加载时，执行
        var targetFile = null;
        window.onload = function () {
            $('#detect_img').attr("width", "");
            $('#detect_img').attr("height", "");
        }

        $("#rapid_face").on('change', function (){
            targetFile = document.getElementById("rapid_face").files[0];
            faceCheck();
        });

        $("html").on("dragover", function(event) {
            event.preventDefault();
            event.stopPropagation();
            $(this).addClass('dragging');
        });

        $("html").on("dragleave", function(event) {
            event.preventDefault();
            event.stopPropagation();
            $(this).removeClass('dragging');
        });

        $("html").on("drop", function(event) {
            event.preventDefault();
            event.stopPropagation();
            let trans = event.originalEvent.dataTransfer;
            handleData(trans);
        });

        $('html').on('paste', function (e) {
            let trans = e.originalEvent.clipboardData;
            handleData(trans);
        });

        function handleData(trans) {
            if (trans.items) {
                for (let i = 0; i < trans.items.length; i++) {
                    // If dropped items aren't files, reject them
                    if (trans.items[i].kind === 'file') {
                        targetFile = trans.items[i].getAsFile();
                        console.log(`handleData: items[${i}].name = ${targetFile.name}`);
                        faceCheck();
                        return;
                    }
                }
            } else {
                // Use DataTransfer interface to access the file(s)
                for (let i = 0; i < trans.files.length; i++) {
                    targetFile = trans.files[i];
                    console.log(`handleData: files[${i}].name = ${targetFile.name}`);
                    faceCheck();
                    return;
                }
            }
        }

        function faceCheck(){
            if (!targetFile){
                return;
            }

            // 判断图像格式是否匹配
            let imageName = targetFile.name;
            let index = imageName.lastIndexOf('.');
            let extName = imageName.substr(index + 1);
            let imgArr = ['jpg', 'bmp', 'png', 'jpeg'];
            if (!(imgArr.includes(extName.toLocaleLowerCase()))){
                alert("图像文件格式不支持！");
                return;
            }

            // 判断图像大小是否符合
            let imageSize = targetFile.size / 1024 / 1024;
            if (imageSize >= 3) {
                alert("图像大小超过3M！");
                return;
            }
            var reader = new FileReader();
            reader.onload = function(e){
                $("#detect_img").attr('src', reader.result);
                $("#detect_img").attr("width", "95%");
                $("#detect_img").attr("height", "100%");
            }
            reader.readAsDataURL(targetFile)
        }
        function faceSave(){
            if (!targetFile){
                return;
            } 
            const formData = new FormData();
            formData.append('file', targetFile);
            formData.append('name', $("#name").val());
            formData.append('uuid', $("#uuid").val());
            //提交
            $.ajax(
                {
                    url:"/api/face/train",
                    type:"POST",
                    data: formData,
                    contentType: false,  // 必须设置
                    processData: false,  // 必须设置
                    beforeSend:function(){
                        $("#wrapper").show();
                    },
                    success:function (result) {
                        var data = JSON.parse(result);
                        $("#wrapper").hide();
                        alert(data['msg']);
                        $("#name").val("")
                        $("#uuid").val("")
                        $("#detect_img").attr('src', '');
                    }
                }
            );
        }
    </script>
</body>
</html>